package org.steven.crm.core.auth;

import org.steven.crm.core.auth.dto.GrantTokenRequest;
import org.steven.crm.core.exception.BusinessErrors;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.accesstoken.AccessTokenService;
import org.steven.crm.core.service.authcode.AuthCodeService;
import org.steven.crm.core.service.user.UserService;

import java.util.Map;

/**
 * @Author wuzw
 * @Date 2024/1/10 17:31
 * @Version 1.0
 */
public class UserAuthHandler extends AuthHandler {
    private static UserService userService = new UserService();

    private static AccessTokenService accessTokenService = new AccessTokenService();

    private static AuthCodeService authCodeService = new AuthCodeService();


    @Override
    public Map<String, String> createToken(Map<String, String> client, GrantTokenRequest grantTokenRequest) throws Exception {
        Map<String, String> user = userService.readByMobile(grantTokenRequest.getUsername());
        if (user.isEmpty()) {
            throw new ServiceException(BusinessErrors.USER_NOT_FOUND);
        }

        authCodeService.validate(grantTokenRequest.getUsername(), grantTokenRequest.getCode());

        return accessTokenService.create(client.get("id"), user.get("id"));
    }

    @Override
    protected Map<String, String> authorize(Map<String, String> accessToken)  throws Exception {
        Map<String, String> user = userService.read(accessToken.get("userId"));

        return user;
    }
}
